﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.IO;
using WeChatSDK.WeChatServiceComponent.ServerTokenVerification;
using WeChatSDK.WeChatDto.ServerTokenVerification;
using WeChatSDK.Common;
using BCService.WeChatComponent.WeChatHandleService;
using WeChatSDK.WeChatServiceComponent.Conversation.BaseSupport;
using WeChatSDK.Common.Enums.MessageEncoding;
using BCCommon;

namespace BCTMSRESTful.Controllers
{
    /// <summary>
    /// 微信服务器验证控制器
    /// </summary>
    [Route("api/v1/[controller]")]
    public class WeChatVerificationController : BCTMSRESTfulAPIController
    {
        private readonly IConfiguration configuration;
        private readonly IWeChatHandleService weChatHandleService;
        public WeChatVerificationController(IConfiguration configuration,IWeChatHandleService weChatHandleService)
        {
            this.configuration = configuration;
            this.weChatHandleService = weChatHandleService;
        }

        #region 微信后台验证地址
        /// <summary>
        /// 微信后台验证地址
        /// 所有请求参数均为微信服务器提供
        /// </summary>
        /// <param name="signature">微信加密签名</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="echostr">随机字符串</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get([FromQuery(Name = "signature")]string signature = null, [FromQuery(Name = "timestamp")]string timestamp = null, [FromQuery(Name = "nonce")]string nonce = null, [FromQuery(Name = "echostr")]string echostr = null)
        {
            if (this.Request.Query.Count == 0)
            {
                return this.Content("Hello, This is WeChatVerification!");
            }
            if (ServerTokenVerificationService.CheckServerToken(signature, timestamp, nonce, echostr, configuration["WeChatService:Token"]))
            {
                return this.Content(echostr);
            }
            else
            {
                return this.Content("");
            }
        }
        #endregion

        #region 接收用户发送消息
        /// <summary>
        /// 用户发送消息后，微信平台自动Post一个请求到这里，并等待响应XML。
        /// 所有请求参数均为微信服务器提供
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromQuery(Name = "msg_signature")]string signature, [FromQuery(Name = "timestamp")]string timestamp = null, [FromQuery(Name = "nonce")]string nonce = null)
        {
            StreamReader reader = new StreamReader(Request.Body);
            string message = reader.ReadToEnd();
            string decryptMessage = string.Empty;
            int errorCode;
            //Log(null, message,string.Empty);
            WXBizMsgCrypt wXBizMsgCrypt = new WXBizMsgCrypt(new BaseSupportService().CreateAccessToken().AccessToken, WeChatInfo.EncodingAESKey, WeChatInfo.AppId);
            //Log(new BaseSupportService().CreateAccessToken().AccessToken, message, string.Empty);
            if (WeChatInfo.EncodingType == WeChatMessageEncodingType.Security)
            {
                errorCode = wXBizMsgCrypt.DecryptMsg(signature, timestamp, nonce, message, ref decryptMessage);
                if (errorCode != 0)
                {
                    throw new Exception(string.Format("微信接收发送信息解密失败，错误编码:{0}", errorCode));
                }
            }
            else
            {
                decryptMessage = message;
            }
            Log(new BaseSupportService().CreateAccessToken().AccessToken, decryptMessage, string.Empty);
            string responseMessage = this.weChatHandleService.HandleMessage(decryptMessage);
            Log(new BaseSupportService().CreateAccessToken().AccessToken, decryptMessage, responseMessage);
            if (responseMessage.Equals("success"))
            {
                return this.Content(responseMessage);
            }
            string encryptResponseMessage = string.Empty;
            if (WeChatInfo.EncodingType == WeChatMessageEncodingType.Security)
            {
                wXBizMsgCrypt.EncryptMsg(responseMessage, timestamp, nonce, ref encryptResponseMessage);
            }
            else
            {
                encryptResponseMessage = responseMessage;
            }
            return this.Content(encryptResponseMessage);
        }
        #endregion

        private void Log(string token,string receiveMessage,string replyMessage)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());

            FileInfo fileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, "wechatReqestLog.txt").ToString());

            if (!fileInfo.Exists)
            {
                using (StreamWriter sw = fileInfo.CreateText())
                {
                    sw.WriteLine("*****************************************");
                    sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                    sw.WriteLine("Token:{0}", token);
                    sw.WriteLine();
                    sw.WriteLine("ReceiveMessage:{0}", receiveMessage);
                    sw.WriteLine();
                    sw.WriteLine("ReplyMessage:{0}", replyMessage);
                }
            }
            else
            {
                using (StreamWriter sw = fileInfo.AppendText())
                {
                    sw.WriteLine("*****************************************");
                    sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                    sw.WriteLine("Token:{0}", token);
                    sw.WriteLine();
                    sw.WriteLine("ReceiveMessage:{0}", receiveMessage);
                    sw.WriteLine();
                    sw.WriteLine("ReplyMessage:{0}", replyMessage);
                }
            }
        }
    }
}
